package com.ssyan.boot.controller;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ssyan
 * @Description 获取请求域中的值
 *              页面跳转的控制层
 * @create 2021/8/18 0:57
 * @Version 1.0
 */
@Controller
public class RequestController {

    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request) {

        request.setAttribute("msg","成功了...");
        request.setAttribute("code",200);
        return "forward:/success"; //转发到 /success请求
    }

    //参数Map、Model的值都会放在请求域中
    @GetMapping("/params")
    public String testParam(Map<String,Object> map,
                            Model model,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        map.put("hello","world666");
        model.addAttribute("world","hello666");
        request.setAttribute("message","HelloWorld");

        response.addCookie(new Cookie("c1","v1"));
        return "forward:/success";
    }

    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute(value = "msg",required = false) String msg,
                       @RequestAttribute(value = "code",required = false) Integer code,
                        HttpServletRequest request) {
        Object msg1 = request.getAttribute("msg");

        Map<String,Object> map = new HashMap<>();

        //测试 /params请求：
        Object hello = request.getAttribute("hello");
        Object world = request.getAttribute("world");
        Object message = request.getAttribute("message");


        map.put("reqMethod_msg",msg1);
        map.put("annotation_msg",msg);
        map.put("annotation_code",code);
        map.put("hello",hello);
        map.put("world",world);
        map.put("message",message);
        return map;
    }

}
